package cn.com.guage.transtation.dao;

import cn.com.guage.transtation.entity.TccAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class TccAccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 查询账户（带悲观锁）
    public TccAccount selectForUpdate(Long accountId) {
        String sql = "SELECT id, balance, frozen, version FROM tcc_account WHERE id = ? FOR UPDATE";
        return jdbcTemplate.queryForObject(sql, new Object[]{accountId}, (rs, rowNum) -> {
            TccAccount account = new TccAccount();
            account.setId(rs.getLong("id"));
            account.setBalance(rs.getInt("balance"));
            account.setFrozen(rs.getInt("frozen"));
            account.setVersion(rs.getInt("version"));
            return account;
        });
    }

    // 更新账户（乐观锁）
    public boolean updateAccount(TccAccount account) {
        String sql = "UPDATE tcc_account SET balance = ?, frozen = ?, version = version + 1 " +
                "WHERE id = ? AND version = ?";
        int rows = jdbcTemplate.update(sql,
                account.getBalance(),
                account.getFrozen(),
                account.getId(),
                account.getVersion());
        return rows > 0;
    }
}